/*
    Document   : cart.js
    Created on : Nov 19, 2012
    Author     : HongDC
*/

var cart = [];
mapCart(); // read items from session storage and map to Cart

var cityArray = [];
cityArray["HCM"] = "Ho Chi Minh";
cityArray["HPG"] = "Hai Phong";
cityArray["HAN"] = "Ha Noi";
cityArray["DNG"] = "Da Nang";
cityArray["OTH"] = "Others";

/** Core functions */
/** -------------------- */

function Book(isbn, title, author, coverUrl, quantity, price) {
    this.isbn = isbn;
    this.title = title;
    this.author = author;
    this.coverUrl = coverUrl;
    this.quantity = quantity;
    this.price = price;
}

// match Order schema, use to send Order info to server
function Order(username, name, address, phone, city) {
    this.username = username;
    this.name = name;
    this.address = address;
    this.phone = phone;
    this.city = city;
    var now = new Date();
    this.orderTime = now.getDate()+"-"+(now.getMonth()+1)+"-"+now.getFullYear();
}

// add an event listener to each element in class btnAddCart
//forEach.call($$(".btnAddCart"), function(el) {
//    el.addEventListener('click', function(e) {
//        var d = e.target.dataset;
//        var book = new Book(d.isbn, d.title, d.author, d.cover, 1, d.price);
//        console.log(book);
//        // Check existing in cart
//        var already = false;
//        for (var i = 0; i < cart.length; i++) {
//            if (cart[i].isbn == book.isbn) {
//                alert("This book is already in your cart.");
//                already = true;
//                break;
//            }
//        };
//        // If new, add
//        if (!already) {
//            cart.push(book); // add to associative array with id = isbn
//            console.log(cart);
//            makeStorage("write");
//            mapCart();
//            alert("This title is added in your cart. \nYou may add more copies from the cart.");
//        }
//    }, false);
//});

function addToCart(target) {
    var d = target.dataset;
    var book = new Book(d.isbn, d.title, d.author, d.cover, 1, d.price);
    console.log(book);
    // Check existing in cart
    var already = false;
    for (var i = 0; i < cart.length; i++) {
        if (cart[i].isbn == book.isbn) {
            alert("This book is already in your cart.");
            already = true;
            break;
        }
    };
    // If new, add
    if (!already) {
        cart.push(book); // add to associative array with id = isbn
        console.log(cart);
        makeStorage("write");
        mapCart();
        alert("This title is added in your cart. \nYou may add more copies from the cart.");
    }
}

// Map data between JS object and DOM
function mapCart() {
    makeStorage("read");
    $$(".cart")[0].innerHTML = "";
    for (var i = cart.length - 1; i >= 0; i--) {
        var bookHtml =
        '<div>'+
        '<img src="'+cart[i].coverUrl+'" alt="">'+
        '<div class="desc">'+
        '<div class="title">'+cart[i].title+'</div>'+
        '<div class="author">'+cart[i].author+'</div>'+
        '<div class="calc">'+
        '<span>$'+cart[i].price+' x</span>'+
        '<input type="number" min="1" max="5" pattern="/^\d{1}$/" step="1" data-isbn="'+cart[i].isbn+'" onchange="setQuantity(this.dataset.isbn, this.value)" value="'+cart[i].quantity+'">'+
        '<input type="button" onclick="removeFromCart(\''+cart[i].isbn+'\')" value="X">'+
        '</div>'+
        '</div>'+
        '</div>';
        $$(".cart")[0].innerHTML += bookHtml;
    };
}

function updateCartStatus() {
    $$(".cart-items")[0].innerHTML = countItems();
    $$(".cart-total")[0].innerHTML = countPrices();
}

function checkOut() {
    if (cart.length != 0) {
        var itemsHtml = "";
        for (i = 0; i < cart.length; i++) {
            itemsHtml += '<tr>'+
                '<td>'+(i+1)+'</td><td>'+cart[i].title+'</td><td>'+cart[i].quantity+'</td><td>'+cart[i].price+'</td>'+
            '</tr>';
        }
        $(".dTotalItems").innerHTML = countItems();
        $(".dTotalPrice").innerHTML = countPrices();
        $(".tblItems").innerHTML = itemsHtml;
        // auto fill userinfo if login
        if (typeof sessionStorage.user != "undefined") {
            xmlhttp = setXmlHttpRequest();
            xmlhttp.open("GET","Controller?action=Checkout", true);
            xmlhttp.send();
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    xmlResult = parseXml(xmlhttp.responseText);
                    response = xmlResult.documentElement;
                    var username = response.childNodes[0].textContent;
                    var name = response.childNodes[1].textContent;
                    var address = response.childNodes[2].textContent;
                    var phone = response.childNodes[3].textContent;
                    var form = $("#userInfo");
                    form.elements["name"].value = name;
                    form.elements["phone"].value = phone;
                    form.elements["address"].value = address;
                }
            }
        }
        toggleDialog("#dCheckout");
    } else {
        alert("Sorry!\nYou must have at least one item in cart before you can check out.");
    }
}


$("#userInfo").addEventListener('submit', function(e) {
    e.preventDefault();
    var form = $("#userInfo");
    var name = form.elements["name"].value;
    var phone = form.elements["phone"].value;
    var address = form.elements["address"].value;
    var city = cityArray[form.elements["city"].value];
    var username = sessionStorage.user!="" ? sessionStorage.user : "GUEST";
    var order = new Order(username, name, address, phone, city);
    var orderXml = convertOrderToXml(order);
    var orderDetailXml = convertCartToXml();
    console.log(orderXml);
    console.log(orderDetailXml);
    
    xmlhttp = setXmlHttpRequest();

    xmlhttp.open("POST","Controller?action=Complete", true);

    var params = "order="+orderXml+"&orderDetail="+orderDetailXml;
    //Send the proper header information along with the request
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", params.length);
    xmlhttp.setRequestHeader("Connection", "close");
    xmlhttp.send(params);

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            xmlResult = parseXml(xmlhttp.responseText);
            response = xmlResult.documentElement;
            if (response.childNodes[0].textContent == "OK") {
                var orderId = response.childNodes[1].textContent;
                $(".orderNumber").href += orderId;
                $(".orderNumber").innerHTML = orderId;
                toggleDialog("#dCheckout"); // hide checkout
                toggleDialog("#dSuccess"); // hide success
            } else {
                alert(response.childNodes[1].textContent);
            }
        }
    }
    
});

/** Supporting functions */
/** -------------------- */
function removeFromCart(isbn) {
    var ok = confirm("Are you sure to remove this title from your cart?");
    if (ok == true) {
        for (var i = cart.length - 1; i >= 0; i--) {
            if (cart[i].isbn == isbn) {
                cart.splice(i, 1);
                makeStorage("write");
                mapCart();
            }
        };
    }
}

function setQuantity(isbn, number) {
    for (var i = 0; i < cart.length; i++) {
        if (cart[i].isbn == isbn) {
            cart[i].quantity = number;
        }
    };
    makeStorage("write");
// need to mapCart or not
}

function countItems() {
    var total = 0;
    for (var i = 0; i < cart.length; i++) {
        total += parseInt(cart[i].quantity);
    };
    return total;
}

function countPrices() {
    var total = 0;
    for (var i = 0; i < cart.length; i++) {
        total += parseInt(cart[i].quantity)*parseFloat(cart[i].price);
    };
    return "$"+total.toFixed(2);
}

function makeStorage(action) {
    if (!sessionStorage) {
        alert("Your browser doesn't support sessionStorage.");
    } else {
        switch (action) {
            case "read":
                if (typeof sessionStorage.cart != "undefined")
                    if (sessionStorage.cart != "")
                        cart = JSON.parse(sessionStorage.cart);
                break;
            case "write":
                sessionStorage.cart = JSON.stringify(cart);
                break;
            case "remove":
                sessionStorage.removeItem("cart");
                cart = [];
                break;
        }
        updateCartStatus();
    }
}

function convertCartToXml() {
    var xml = "<OrderDetails xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='http://www.bookstore.net/schema/order' xsi:schemaLocation='http://www.bookstore.net/schema/order OrderSchema.xml'>";
    for (var i = cart.length - 1; i >= 0; i--) {
        xml +=
        '<OrderDetail Isbn="'+cart[i].isbn+'">'+
        '<Quantity>'+cart[i].quantity+'</Quantity>'+
        '</OrderDetail>'
    };
    xml += '</OrderDetails>';
    return xml;
}

function convertOrderToXml(order) {
    var xml = "<Order xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='http://www.bookstore.net/schema/order' xsi:schemaLocation='http://www.bookstore.net/schema/order OrderSchema.xml'>" +
        '<OrderTime>'+order.orderTime+'</OrderTime>'+
        '<City>'+order.city+'</City>'+
        '<Address>'+order.address+'</Address>'+
        '<Phone>'+order.phone+'</Phone>'+
        '<Name>'+order.name+'</Name>'+
        '<Username>'+order.username+'</Username>'+
    '</Order>';
    return xml;
}